{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Python编程基础复习"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.基本变量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "metadata": {},
   "outputs": [],
   "source": [
    "import copy\n",
    "\n",
    "# int\n",
    "a = 10\n",
    "\n",
    "# float\n",
    "b = 10.5\n",
    "\n",
    "# string\n",
    "c = \"Hello, World!\"\n",
    "\n",
    "# boolean\n",
    "d = True\n",
    "e = False\n",
    "\n",
    "# None\n",
    "j = None \n",
    "\n",
    "# complex\n",
    "k = 1 + 2j # 复数\n",
    "\n",
    "# bytes\n",
    "l = b\"Hello, World!\"\n",
    "\n",
    "# frozenset\n",
    "o = frozenset([1, 2, 3, 5, 4, 5])  # 不可修改 集合去重\n",
    "\n",
    "# range\n",
    "p = range(5)  # 范围对象 循环 索引 \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 对列表的基本操作"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "索引操作\n",
      "f[0]: 1\n",
      "切片操作\n",
      "f[0:3]: [1, 2, 3]\n",
      "f[:3]: [1, 2, 3]\n",
      "f[1:]: [2, 3, 4, 5, ['a', 'b']]\n",
      "f[-1]: ['a', 'b']\n",
      "f[-3:]: [4, 5, ['a', 'b']]\n",
      "加法操作\n",
      "f + [6, 7]: [1, 2, 3, 4, 5, ['a', 'b'], 6, 7]\n",
      "乘法操作\n",
      "[1, 2] * 3: [1, 2, 1, 2, 1, 2]\n",
      "f * 2: [1, 2, 3, 4, 5, ['a', 'b'], 1, 2, 3, 4, 5, ['a', 'b']]\n"
     ]
    }
   ],
   "source": [
    "# list\n",
    "f = [1, 2, 3, 4, 5, ['a', 'b']] # 列表 可修改 索引 切片 加法 乘法\n",
    "\n",
    "# 索引\n",
    "print(\"索引操作\")\n",
    "print(f\"f[0]: {f[0]}\")\n",
    "\n",
    "# 切片\n",
    "print(\"切片操作\")\n",
    "print(f\"f[0:3]: {f[0:3]}\") # 左包括 右不包括\n",
    "print(f\"f[:3]: {f[:3]}\")\n",
    "print(f\"f[1:]: {f[1:]}\")\n",
    "print(f\"f[-1]: {f[-1]}\")\n",
    "print(f\"f[-3:]: {f[-3:]}\")\n",
    "\n",
    "\n",
    "# 加法\n",
    "print(\"加法操作\")\n",
    "print(f\"f + [6, 7]: {f + [6, 7]}\")\n",
    "\n",
    "# 乘法\n",
    "print(\"乘法操作\")\n",
    "print(f\"[1, 2] * 3: {[1, 2] * 3}\")\n",
    "print(f\"f * 2: {f * 2}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 对元组的基本操作"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'tuple'>\n",
      "tup: (1, 2, 3, 4, 5)\n",
      "tup[0]: 1\n",
      "试图修改元组\n",
      "TypeError: 'tuple' object does not support item assignment\n",
      "tup[0] = 1\n",
      "tup2: (1, 2, 3, 4, 5, 5, 1, 2, 3, 4, 5)\n",
      "NameError: name 'tup3' is not defined\n",
      "tup[1]: 2\n",
      "tup[-1]: 5\n",
      "tup[:3]: (1, 2, 3)\n",
      "tup[1:3]: (2, 3)\n",
      "内置函数\n",
      "len(f): 6\n",
      "max(f): 5\n",
      "min(f): 1\n",
      "sum(f): 20\n",
      "sorted(f): [1, 2, 3, 4, 5, 5]\n",
      "拷贝\n",
      "f: [1, 2, 3, 4, 5, ['a', 'b', 'c']]\n",
      "f2: [1, 2, 3, 4, 5, ['a', 'b', 'c']]\n",
      "f3: [1, 2, 3, 4, 5, ['a', 'b']]\n"
     ]
    }
   ],
   "source": [
    "# tuple\n",
    "g = (1, 2, 3, 4, 5, 5) # 元组 不可修改\n",
    "\n",
    "# 不加（）也可定义\n",
    "tup = 1, 2, 3, 4, 5\n",
    "print(type(tup))\n",
    "print(f\"tup: {tup}\")\n",
    "print(f\"tup[0]: {tup[0]}\")\n",
    "\n",
    "# 试图修改元组\n",
    "try:\n",
    "    print(\"试图修改元组\")\n",
    "    tup[0] = 10\n",
    "except TypeError as e:\n",
    "    print(f\"TypeError: {e}\")\n",
    "finally:\n",
    "    print(f\"tup[0] = {tup[0]}\")  # 仍然是1\n",
    "\n",
    "# 创建新元组\n",
    "tup2 = g + tup\n",
    "print(f\"tup2: {tup2}\")\n",
    "\n",
    "# 删除元组\n",
    "tup3 = \"a\", \"b\", \"c\"\n",
    "del tup3\n",
    "try:\n",
    "    print(tup3)\n",
    "except NameError as e:\n",
    "    print(f\"NameError: {e}\")\n",
    "\n",
    "# 索引 截取\n",
    "print(f\"tup[1]: {tup[1]}\")\n",
    "print(f\"tup[-1]: {tup[-1]}\")\n",
    "print(f\"tup[:3]: {tup[:3]}\")\n",
    "print(f\"tup[1:3]: {tup[1:3]}\") \n",
    "\n",
    "\n",
    "# 内置函数\n",
    "print(\"内置函数\")\n",
    "print(f\"len(f): {len(g)}\") # 长度\n",
    "print(f\"max(f): {max(g)}\") # 最大值\n",
    "print(f\"min(f): {min(g)}\") # 最小值\n",
    "print(f\"sum(f): {sum(g)}\") # 求和\n",
    "print(f\"sorted(f): {sorted(g)}\") # 排序\n",
    "\n",
    "# 拷贝\n",
    "print(\"拷贝\")\n",
    "f2 = f.copy() # 浅拷贝\n",
    "f3 = copy.deepcopy(f) # 深拷贝\n",
    "\n",
    "f[-1].append('c') # 修改原列表\n",
    "print(f\"f: {f}\") # f\n",
    "print(f\"f2: {f2}\") # f2\n",
    "print(f\"f3: {f3}\") # f3\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 对字典的基本操作"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "访问字典\n",
      "i : {'name': 'Alice', 'age': 30, 'city': 'New York', 'hobbies': ['reading', 'traveling', 'cooking']}\n",
      "i['name']: Alice\n",
      "修改字典\n",
      "i['age']: 31\n",
      "内置函数\n",
      "len(i): 4\n",
      "i.keys(): dict_keys(['name', 'age', 'city', 'hobbies'])\n",
      "i.values(): dict_values(['Alice', 31, 'New York', ['reading', 'traveling', 'cooking']])\n",
      "i.items(): dict_items([('name', 'Alice'), ('age', 31), ('city', 'New York'), ('hobbies', ['reading', 'traveling', 'cooking'])])\n",
      "i.get('name'): Alice\n",
      "i: {'name': 'Bob', 'age': 31, 'city': 'New York', 'hobbies': ['reading', 'traveling', 'cooking', 'swimming']}\n",
      "copy_i 浅拷贝: {'name': 'Alice', 'age': 31, 'city': 'New York', 'hobbies': ['reading', 'traveling', 'cooking', 'swimming']}\n"
     ]
    }
   ],
   "source": [
    "i = {\n",
    "    \"name\": \"Alice\",\n",
    "    \"age\": 30,\n",
    "    \"city\": \"New York\",\n",
    "    \"hobbies\": [\"reading\", \"traveling\", \"cooking\"],\n",
    "}\n",
    "\n",
    "# 访问字典\n",
    "print(\"访问字典\")\n",
    "print(f\"i : {i}\")\n",
    "print(f\"i['name']: {i['name']}\")\n",
    "\n",
    "# 修改字典\n",
    "print(\"修改字典\")\n",
    "i[\"age\"] = 31\n",
    "print(f\"i['age']: {i['age']}\")\n",
    "\n",
    "# 内置函数\n",
    "print(\"内置函数\")\n",
    "print(f\"len(i): {len(i)}\") # 长度\n",
    "print(f\"i.keys(): {i.keys()}\") # 键\n",
    "print(f\"i.values(): {i.values()}\") # 值\n",
    "print(f\"i.items(): {i.items()}\") # 键值对\n",
    "print(f\"i.get('name'): {i.get('name')}\") # 获取值\n",
    "\n",
    "copy_i = i.copy() # 浅拷贝\n",
    "\n",
    "i[\"name\"] = \"Bob\" # 修改原字典\n",
    "i[\"hobbies\"].append(\"swimming\") # 修改原字典的列表\n",
    "\n",
    "print(f\"i: {i}\") # 原字典\n",
    "print(f\"copy_i 浅拷贝: {copy_i}\") # 浅拷贝\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 对集合的基本操作"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "h: {1, 2, 3, 4, 5}\n",
      "set_1: {'f', 'd', 'a', 'w'}\n",
      "h: {1, 2, 3, 4, 5, 6}\n",
      "h: {1, 2, 3, 4, 5, 6, 7, 8}\n",
      "h: {1, 2, 3, 4, 5, 6, 7, 8, 9}\n",
      "h: {2, 3, 4, 5, 6, 7, 8, 9}\n",
      "set_1: {'f', 'd', 'a', 'w'}\n",
      "h: {3, 4, 5, 6, 7, 8, 9}\n",
      "set_1: set()\n"
     ]
    }
   ],
   "source": [
    "# 无序的不重复的元素序列\n",
    "# set\n",
    "h = {1, 2, 3, 4, 5, 5}\n",
    "print(f\"h: {h}\") # 集合 去重\n",
    "\n",
    "set_1 = set('dwadwaffafawfa')\n",
    "print(f\"set_1: {set_1}\") # 集合 去重\n",
    "\n",
    "h.add(6) # 添加元素\n",
    "print(f\"h: {h}\")\n",
    "\n",
    "h.update({7, 8}) # 添加多个元素\n",
    "print(f\"h: {h}\")\n",
    "\n",
    "h.update({9: 10}) # 添加字典\n",
    "print(f\"h: {h}\")\n",
    "\n",
    "h.remove(1) # 删除元素\n",
    "print(f\"h: {h}\")\n",
    "\n",
    "set_1.discard(1) # 删除元素\n",
    "print(f\"set_1: {set_1}\") # 集合 去重\n",
    "\n",
    "h.pop() # 随机删除一个元素\n",
    "print(f\"h: {h}\") # 集合 去重\n",
    "\n",
    "set_1.clear() # 清空集合\n",
    "print(f\"set_1: {set_1}\") # 集合 去重"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "args: (1, 2, 3)\n",
      "kwargs: {'a': 4, 'b': 5}\n"
     ]
    }
   ],
   "source": [
    "# 收集参数\n",
    "\n",
    "def collect_args(*args, **kwargs):\n",
    "    print(f\"args: {args}\")  # 元组的打包\n",
    "    print(f\"kwargs: {kwargs}\")\n",
    "collect_args(1, 2, 3, a=4, b=5) # 收集参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "funB x: 800\n",
      "funA x: 250\n",
      "TypeError: 'str' object is not callable\n",
      "str被赋值为字符串了，导致内置函数str失效了\n"
     ]
    }
   ],
   "source": [
    "def funA():\n",
    "    x = 250\n",
    "    def funB():\n",
    "        x = 800\n",
    "        print(f\"funB x: {x}\")\n",
    "    funB()\n",
    "    print(f\"funA x: {x}\")\n",
    "\n",
    "funA()\n",
    "\n",
    "# 作用域 Local > Enclosing > Global > Built-in lEGB\n",
    "# Local: 函数内部\n",
    "# Enclosing: 嵌套函数\n",
    "# Global: 全局变量\n",
    "# Built-in: 内置函数\n",
    "\n",
    "str = \"摧毁内置函数\"\n",
    "try:\n",
    "    str(520)\n",
    "except TypeError as e:\n",
    "    print(f\"TypeError: {e}\")\n",
    "    print(\"str被赋值为字符串了，导致内置函数str失效了\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "调用输入函数前\n",
      "输入函数的参数: 5, 10\n",
      "调用输入函数后\n",
      "Result: 15\n",
      "------------------\n",
      "调用输入函数前\n",
      "输入函数的参数: 5, 10\n",
      "调用输入函数后\n"
     ]
    }
   ],
   "source": [
    "# 装饰器\n",
    "def decorator(func):\n",
    "    def wrapper(*args, **kwargs):\n",
    "        print(\"调用输入函数前\")\n",
    "        result = func(*args, **kwargs)\n",
    "        print(\"调用输入函数后\")\n",
    "        return result\n",
    "    return wrapper\n",
    "\n",
    "@decorator\n",
    "def my_function(x:int, y:int) -> int:\n",
    "    print(f\"输入函数的参数: {x}, {y}\")\n",
    "    return x + y\n",
    "result = my_function(5, 10)\n",
    "print(f\"Result: {result}\")\n",
    "\n",
    "print(\"------------------\")\n",
    "\"\"\" 其实等价于下面样操作 \"\"\"\n",
    "\n",
    "def my_function2(x, y):\n",
    "    print(f\"输入函数的参数: {x}, {y}\")\n",
    "    return x + y\n",
    "\n",
    "decorator2 = decorator(my_function2)\n",
    "result2 = decorator2(5, 10)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.类与对象相关"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "我叫小狗\n"
     ]
    }
   ],
   "source": [
    "# 继承\n",
    "class Animal:\n",
    "    def __init__(self, name):\n",
    "        self.name = name\n",
    "\n",
    "    def speak(self):\n",
    "        print(f\"我叫{self.name}\")\n",
    "\n",
    "class Dog(Animal):\n",
    "    def __init(self, name):\n",
    "        super().__init__(name)\n",
    "\n",
    "D = Dog(\"小狗\")\n",
    "D.speak() # 我叫小狗"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Circle的面积是: 78.5\n",
      "Rectangle的面积是: 24\n"
     ]
    }
   ],
   "source": [
    "# 重写 多态\n",
    "class Shape():\n",
    "    def __init__(self, name):\n",
    "        self.name = name\n",
    "    def area(self):\n",
    "        pass\n",
    "\n",
    "class Circle(Shape):\n",
    "    def __init__(self, radius):\n",
    "        super().__init__(\"Circle\") # 调用父类的构造函数\n",
    "        self.radius = radius\n",
    "    def area(self): # 重写父类的方法\n",
    "        return 3.14 * self.radius ** 2\n",
    "    \n",
    "class Rectangle(Shape):\n",
    "    def __init__(self, width, height):\n",
    "        super().__init__(\"Rectangle\")\n",
    "        self.width = width\n",
    "        self.height = height\n",
    "    def area(self):\n",
    "        return self.width * self.height\n",
    "\n",
    "shapes = [Circle(5), Rectangle(4, 6)]\n",
    "for shape in shapes:\n",
    "    print(f\"{shape.name}的面积是: {shape.area()}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "pytorch",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.17"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
